package com.thinkgem.jeesite.modules.report.service;

import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.modules.book.entity.BkBookstore;
import com.thinkgem.jeesite.modules.report.dao.BookReportDao;
import com.thinkgem.jeesite.modules.report.entity.GeneralLedgerDetail;
import com.thinkgem.jeesite.modules.report.entity.LedgerSearch;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 报表
 *
 * @author thinkgem
 * @version 2014-05-16
 */
@Service
@Transactional(readOnly = true)
public class BookReportService extends CrudService<BookReportDao, BkBookstore>{
    public Map<String, Double> getPurchaseLedgerDetailCount(LedgerSearch ledgerSearch){
        String sql = getSql(ledgerSearch);
        return dao.getPurchaseLedgerDetailCount(sql);
    }

    public List<GeneralLedgerDetail> getPurchaseLedgerDetail(LedgerSearch ledgerSearch, boolean isAll){
        String sql = getSql(ledgerSearch);
        if(!isAll){
            sql += " limit 100 ";
        }
        return dao.getPurchaseLedgerDetail(sql);
    }

    private String getSql(LedgerSearch ledgerSearch){
        String searchType  = ledgerSearch.getSearchType();
        String bkType  = ledgerSearch.getBkType();
        String rangeType  = ledgerSearch.getRangeType();
        String begin  = ledgerSearch.getBegin();

        Date beginDate  = ledgerSearch.getBeginDate();
        Date endDate  = ledgerSearch.getEndDate();
        String store = ledgerSearch.getStore();

        String sql = "";
        if("3".equals(searchType) && StringUtils.isNotBlank(bkType)){
            sql += " AND SUBSTRING(sb.classcode, 1, 1) = '"+bkType+"'";
        }

        if("1".equals(rangeType)){
            sql += " AND pb.batch_date >= '"+beginDate+"' AND pb.batch_date <= '"+ endDate +"'";
        }
        else if("2".equals(rangeType)){
            sql += " AND pb.batch_number = '"+ begin + "' ";
        }
        else if("3".equals(rangeType)){
            sql += " AND pb.invoice =  '"+ begin + "' ";
        }

        if(StringUtils.isNotBlank(store)){
            sql += " AND sb.store =  '"+ store + "' ";
        }
        sql += " AND sb.del_flag =  '0' ";
        return sql;
    }
}
